<!doctype html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <link rel="icon" href="favicon.ico" type="image/x-icon">
  <title>Python编程纠错助手</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@11.7.0/styles/github.min.css">
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.7.0/lib/highlight.min.js"></script>
</head>
<body class="bg-gradient-to-br from-blue-50 to-indigo-100 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <!-- 头部区域 -->
        <div class="bg-white rounded-2xl shadow-xl p-6 mb-6 backdrop-blur-sm bg-opacity-95">
            <div class="flex flex-col lg:flex-row items-center justify-between gap-4">
                <div class="flex items-center gap-4">
                    <div class="w-12 h-12 bg-gradient-to-r from-blue-500 to-indigo-600 rounded-xl flex items-center justify-center">
                        <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"></path>
                        </svg>
                    </div>
                    <h1 class="text-3xl lg:text-4xl font-bold bg-gradient-to-r from-blue-600 to-indigo-700 bg-clip-text text-transparent">
                        Python编程纠错助手
                    </h1>
                </div>
                <div class="flex items-center gap-3">
                    <label for="modelSelector" class="text-gray-700 font-semibold text-lg">选择模型：</label>
                    <select id="modelSelector" class="bg-white border-2 border-gray-300 rounded-xl px-4 py-2 text-gray-700 font-medium focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 min-w-[280px] shadow-sm">
                        <!-- 模型选项将通过JavaScript动态加载 -->
                    </select>
                </div>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="grid lg:grid-cols-2 gap-6">
            <!-- 左侧代码输入区域 -->
            <div class="bg-white rounded-2xl shadow-xl p-6 backdrop-blur-sm bg-opacity-95">
                <div class="flex items-center gap-3 mb-4">
                    <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center">
                        <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                        </svg>
                    </div>
                    <h2 class="text-xl font-bold text-gray-900">输入Python代码</h2>
                </div>
                <div class="mb-6">
                    <textarea id="pythonCode" rows="20" class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl font-mono text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-200 bg-gray-50 resize-none" placeholder="在这里粘贴您的Python代码..."></textarea>
                </div>
                <div class="flex justify-center">
                    <button id="submitBtn" class="bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white font-bold py-3 px-8 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transform hover:scale-105 transition-all duration-200 shadow-lg hover:shadow-xl">
                        <span class="flex items-center gap-2">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                            </svg>
                            分析代码
                        </span>
                    </button>
                </div>
            </div>

            <!-- 右侧分析结果区域 -->
            <div class="bg-white rounded-2xl shadow-xl p-6 backdrop-blur-sm bg-opacity-95">
                <div class="flex items-center gap-3 mb-4">
                    <div class="w-8 h-8 bg-purple-100 rounded-lg flex items-center justify-center">
                        <svg class="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                    </div>
                    <h2 class="text-xl font-bold text-gray-900">分析结果</h2>
                </div>
                <div id="analysisResult" class="bg-gray-50 rounded-xl p-4 max-h-[600px] overflow-y-auto">
                    <div id="placeholderMessage" class="text-gray-400 italic flex flex-col items-center justify-center h-32">
                        <svg class="w-12 h-12 mb-3 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                        点击"分析代码"按钮查看分析结果...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-white mt-8 py-6 border-t border-gray-200">
        <div class="container mx-auto px-4 text-center">
            <p class="text-gray-400">© 2025 Python编程纠错助手 | hduzn</p>
        </div>
    </footer>

    <script>
        // 获取当前页面的文件名
        const currentPage = window.location.pathname.split('/').pop() || 'index.html';

        // 加载配置文件
        async function loadConfig() {
            try {
                const response = await fetch('config.json');
                const config = await response.json();
                return config;
            } catch (error) {
                console.error('Error loading config:', error);
                return null;
            }
        }

        document.addEventListener('DOMContentLoaded', async () => {
            const config = await loadConfig();
            if (!config) {
                console.error('Failed to load configuration');
                return;
            }

            // 获取当前页面的配置
            const pageConfig = config.page_config[currentPage];
            const apiConfig = config.api_config[pageConfig.default_api];

            // 初始化提示选择器（如果页面有多个可用提示）
            const promptSelector = document.getElementById('promptSelector');
            if (promptSelector && pageConfig.available_prompts) {
                // 清空现有选项
                promptSelector.innerHTML = '';
                
                // 添加可用的提示选项
                pageConfig.available_prompts.forEach(promptKey => {
                    const prompt = config.system_prompts[promptKey];
                    const option = document.createElement('option');
                    option.value = promptKey;
                    option.textContent = prompt.name;
                    if (promptKey === pageConfig.default_prompt) {
                        option.selected = true;
                    }
                    promptSelector.appendChild(option);
                });
            }

            // 初始化模型选择器
            const modelSelector = document.getElementById('modelSelector');
            if (modelSelector && pageConfig.available_apis) {
                // 清空现有选项
                modelSelector.innerHTML = '';
                
                // 添加可用的API模型选项
                pageConfig.available_apis.forEach(apiKey => {
                    const option = document.createElement('option');
                    option.value = apiKey;
                    // 显示API名称和对应的模型名称
                    option.textContent = `${config.api_config[apiKey].name} (${config.api_config[apiKey].model})`;
                    if (apiKey === pageConfig.default_api) {
                        option.selected = true;
                    }
                    modelSelector.appendChild(option);
                });
            }

            // 存储当前选择的API
            let currentApiKey = pageConfig.default_api;
            let currentApiConfig = apiConfig;

            // 监听模型选择变化
            if (modelSelector) {
                modelSelector.addEventListener('change', function() {
                    currentApiKey = this.value;
                    currentApiConfig = config.api_config[currentApiKey];
                    console.log(`已切换到模型: ${currentApiKey}`);
                });
            }

            document.getElementById('submitBtn').addEventListener('click', async () => {
                const pythonCode = document.getElementById('pythonCode').value;
                const analysisResultDiv = document.getElementById('analysisResult');
                const placeholderMessage = document.getElementById('placeholderMessage');

                // 隐藏占位消息
                if (placeholderMessage) {
                    placeholderMessage.style.display = 'none';
                }

                // 显示加载中的消息
                analysisResultDiv.innerHTML = `
                    <div class="flex flex-col items-center justify-center h-32">
                        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mb-3"></div>
                        <p class="text-gray-500 font-medium">正在分析代码，请稍候...</p>
                    </div>
                `;

                try {
                    // 获取当前选中的提示（如果有选择器）或使用默认提示
                    const selectedPrompt = promptSelector ? 
                        promptSelector.value : 
                        pageConfig.default_prompt;

                    const response = await fetch(currentApiConfig.url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${currentApiConfig.api_key}`
                        },
                        body: JSON.stringify({
                            model: currentApiConfig.model,
                            messages: [
                                {
                                    role: "system",
                                    content: config.system_prompts[selectedPrompt].content
                                },
                                {
                                    role: "user",
                                    content: `请分析以下Python代码，指出错误并提供简单的解释：\n\n${pythonCode}`
                                }
                            ]
                        })
                    });

                    const data = await response.json();
                    const analysis = data.choices[0].message.content;

                    // 使用marked将Markdown转换为HTML
                    analysisResultDiv.innerHTML = marked.parse(analysis);

                    // 应用代码高亮
                    document.querySelectorAll('pre code').forEach((block) => {
                        hljs.highlightBlock(block);
                    });
                } catch (error) {
                    analysisResultDiv.innerHTML = `
                        <div class="flex flex-col items-center justify-center h-32">
                            <svg class="w-12 h-12 mb-3 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                            <p class="text-red-500 font-medium text-center">抱歉，分析过程中出现错误。<br>请稍后再试。</p>
                        </div>
                    `;
                    console.error('Error:', error);
                }
            });
        });
    </script>
</body>
</html>